﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RockCompany.Common.Lib;
using RockCompany.Common.Forms;
using RockCompany.Master.Constant;
using RockCompany.Master.Model;
using RockCompany.Common.Constant;
using RockCompany.Master.DTO;
using RockCompany.Master.Validator;
using RockCompany.Master.Controller;
using RockCompany.Master.View;
using System.Reflection;
using System.Collections;

namespace RockCompany.Master.View
{
    public partial class SW01A : ParentFrm
    {
        private Translator trans;
        private string sUserName; // login user
        private UserAuthenticate uAuth;
        private SI01 frm_MatsManage; // Material form
        private SW02 frm_QLTienDo; // QL Tien do form
        // Controller
        private SW01FormCtrl ctrlSW01 = new SW01FormCtrl();
        // Model
        private SW01FormModel modelSW01;

        // Material list, properties of material datagridview
        public List<PropertyInfo> properties;
        public DataTable matList;

        // Interface with SW01B
        public bool isNew = true;
        public string choosenLotNo = CommonConstantIF.BLANK;

        public Translator translator
        {
            get { return trans; }
        }

        public SW01A()
        {
            InitializeComponent();
        }

        public SW01A(Translator translator, string sUName, Form caller)
            : base(sUName, caller)
        {
            InitializeComponent();

            this.trans = translator;
            trans.controlTranslate(this);
            uAuth = new UserAuthenticate();
            uAuth.setRights(this, sUName);
            sUserName = sUName;
            modelSW01 = new SW01FormModel();
            modelSW01.translator = trans;
            properties = CreateMaterialProperties();

            // Read only list
            List<string> lst = new List<string>();
            lst.Add(CONG_LENH_SX.N_SO_LO);
            lst.Add(CONG_LENH_SX_CT.N_MA_NVL_VTU);
            lst.Add(NGUYEN_VLIEU_VTU_DTO.N_DON_GIA);
            lst.Add(NGUYEN_VLIEU_VTU_DTO.N_TY_GIA);

            modelSW01.buildDataGrid(dgvMaterialList, properties, lst);
            matList = modelSW01.buildEmptyDataTable(properties);
            matList.Columns[CONG_LENH_SX_CT.N_TONG_LUONG_SX].Expression = CONG_LENH_SX_CT.N_SO_LAN + "*" + CONG_LENH_SX_CT.N_TRONG_LUONG;
        }

        public List<PropertyInfo> CreateMaterialProperties()
        {
            NGUYEN_VLIEU_VTU_DTO nvlDTO = new NGUYEN_VLIEU_VTU_DTO();
            CONG_LENH_SX_CT clctDTO = new CONG_LENH_SX_CT();

            List<PropertyInfo> properties = new List<System.Reflection.PropertyInfo>();
            properties.Add(nvlDTO.GetType().GetProperty(NGUYEN_VLIEU_VTU_DTO.N_CHON));
            properties.Add(nvlDTO.GetType().GetProperty(NGUYEN_VLIEU_VTU_DTO.N_MA_NVL_VTU));
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_SO_LO));
            
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_TY_LE));
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_TRONG_LUONG));
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_SO_LAN));
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_TONG_LUONG_SX));

            properties.Add(nvlDTO.GetType().GetProperty(NGUYEN_VLIEU_VTU_DTO.N_DON_GIA));
            properties.Add(nvlDTO.GetType().GetProperty(NGUYEN_VLIEU_VTU_DTO.N_TY_GIA));
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_EX_RATE));
            properties.Add(clctDTO.GetType().GetProperty(CONG_LENH_SX_CT.N_GHI_CHU));


            return properties;
        }

        private void SW01A_Load(object sender, EventArgs e)
        {
            if (!this.isNew)
            {
                // Load WO and WO details
                ctrlSW01.LoadWO(this, this.choosenLotNo);

                // Allow user to update easily

                this.tbLotNo.Enabled = false;
                //this.tbProductNo.Enabled = false;
                //this.cbParentLotNo.Enabled = false;
                this.cbWOType.Enabled = false;
                bool isNewType = SW01AConst.CB_NEW_TYPE.Equals(cbWOType.Text);
                dgvMaterialList.Columns[CONG_LENH_SX_CT.N_EX_RATE].Visible = isNewType;
                dgvMaterialList.Columns[NGUYEN_VLIEU_VTU_DTO.N_TY_GIA].Visible = isNewType;
                dgvMaterialList.Columns[NGUYEN_VLIEU_VTU_DTO.N_DON_GIA].Visible = isNewType;
                //this.picProductionDate.Enabled = false;
                //this.btSave.Enabled = false;
            }
            else
            {
                ctrlSW01.addWOTypeToCombo(cbWOType);
            }
            TotalOfWeight();
        }
        

        private void btSave_Click(object sender, EventArgs e)
        {
            if (validate(SW01AConst.F_ADD_CD) && InforDialog.showConfirmBox(trans.getMessageCaption(CommonConstantIF.CONFIRM_CAPTION)
                                                                         , trans.getMessageCaption(CommonConstantIF.SW01A_ADD_CONFIRM)))
            {
                // Calculate price of WO
                btXemGia_Click(sender, e);

                bool isSuccess = false;
                if (this.isNew)
                {
                    isSuccess = modelSW01.InsertWorkOrder(CreateWODTO(SW01AConst.F_ADD_CD), sUserName);
                }
                else
                {
                    isSuccess = modelSW01.UpdateWO(CreateWODTO(SW01AConst.F_ADD_CD), sUserName);
                }
                if (isSuccess)
                {
                    InforDialog.showMessageBox(trans.getMessageCaption(CommonConstantIF.InforBoxCap),
                                                trans.getMessageCaption(CommonConstantIF.OPERATION_SUCCESS));

                }
                else
                {
                    InforDialog.showMessageBox(trans.getMessageCaption(CommonConstantIF.InforBoxCap),
                                                trans.getMessageCaption(CommonConstantIF.OPERATION_FAILURE));
                }
            }
        }


        private void btXemGia_Click(object sender, EventArgs e)
        {
            if (cbWOType.Text.Equals(SW01AConst.CB_MODIFICATION_TYPE)) { return; }

            //((Đơn giá x tổng lượng SX x Tỉ giá) / Tổng lượng nhập kho) / Hiệu suất
            decimal tongNK = Util.parseDecimal(tbTongSLNK.Text);
            decimal hieuSuat = Util.parseDecimal(tbHieuSuat.Text);

            double gia = 0.0;

            if (hieuSuat != 0 && tongNK != 0)
            {
                decimal totalOfMatAmt = 0;
                foreach (DataRow r in this.matList.Rows)
                {
                    decimal donGia = Util.parseDecimal(r[NGUYEN_VLIEU_VTU_DTO.N_DON_GIA]);
                    decimal tongSX = Util.parseDecimal(r[CONG_LENH_SX_CT.N_TONG_LUONG_SX]);
                    decimal tyGia = 1;
                    if ("USD".Equals(r[NGUYEN_VLIEU_VTU_DTO.N_TY_GIA].ToString()))
                    {
                        tyGia = Util.parseDecimal(r[CONG_LENH_SX_CT.N_EX_RATE]);
                    }
                    totalOfMatAmt += donGia * tyGia * tongSX;
                }

                if (Double.TryParse((totalOfMatAmt / (hieuSuat * tongNK)).ToString(), out gia))
                {
                    tbGiaCL.Text = string.Format("{0:N2}", gia);
                }
                
            }
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            this.Hide();
            SI04 inventory = new SI04(trans, sUserName, this);
            inventory.callChooser(SI04Const.NO_MAT_TYPE);
            if (inventory.ShowDialog(this) == DialogResult.OK)
            {
                DataTable selectedMats = inventory.getSelectedMatsNo();
                DataTable tempBD = modelSW01.buildSelectedMatsList(selectedMats);
                if (tempBD.Rows.Count > 0)
                {
                    List<string> lst = new List<string>();
                    lst.Add(CONG_LENH_SX_CT.N_MA_NVL_VTU);
                    lst.Add(NGUYEN_VLIEU_VTU_DTO.N_DON_GIA);
                    lst.Add(NGUYEN_VLIEU_VTU_DTO.N_TY_GIA);

                    // Copy material code
                    modelSW01.copyDataTable(tempBD, matList, lst);
                    CommonModel.bindDGV(dgvMaterialList, matList);
                    TotalOfWeight();
                }
                // Dispose frm_material
                inventory.Dispose();
                this.Show();
            }

            //this.Hide();
            //frm_MatsManage = new SI01(trans, sUserName, this);
            //frm_MatsManage.callChooser(true);
            //if (frm_MatsManage.ShowDialog(this) == DialogResult.OK)
            //{
            //    DataTable selectedMats = frm_MatsManage.getSelectedMatsNo();
            //    List<string> lst = new List<string>();
            //    lst.Add(CONG_LENH_SX_CT.N_MA_NVL_VTU);
            //    lst.Add(NGUYEN_VLIEU_VTU_DTO.N_DON_GIA);
            //    lst.Add(NGUYEN_VLIEU_VTU_DTO.N_TY_GIA);
                
            //    // Copy material code
            //    modelSW01.copyDataTable(selectedMats, matList, lst);
            //    CommonModel.bindDGV(dgvMaterialList, matList);
            //    TotalOfWeight();
            //    // Dispose frm_material
            //    frm_MatsManage.Dispose();
            //    this.Show();
            //}
        }


        private void btAddBTP_Click(object sender, EventArgs e)
        {
            this.Hide();
            frm_QLTienDo = new SW02(trans, sUserName, this);
            frm_QLTienDo.callChooser(true);
            if (frm_QLTienDo.ShowDialog(this) == DialogResult.OK)
            {
                DataTable selectedMats = frm_QLTienDo.getSelectedBTPs();
                

                modelSW01.copyDataTable2(selectedMats, this.matList, new string[] { CONG_LENH_SX_CT.N_SO_LO, CONG_LENH_SX_CT.N_MA_MAU }
                                                                    , new string[] { CONG_LENH_SX_CT.N_SO_LO, CONG_LENH_SX_CT.N_MA_NVL_VTU });
                CommonModel.bindDGV(dgvMaterialList, this.matList);
                TotalOfWeight();
                // Dispose QLTiendo form
                frm_QLTienDo.Dispose();
            }
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbWOType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SW01AConst.MODIFICATION_TYPE == cbWOType.SelectedIndex)
            {
                DataTable res = modelSW01.GetUnapprovedLotNos();
                CommonModel.bindCombo(cbParentLotNo, SW01AConst.SO_LO, "", res);
                // Reset fields
                ResetFields();
            }
            else if (SW01AConst.NEW_TYPE == cbWOType.SelectedIndex)
            {
                cbParentLotNo.DataSource = null;
                // Reset fields
                ResetFields();
            }

            // Hide and Show column
            dgvMaterialList.Columns[CONG_LENH_SX_CT.N_SO_LAN].Visible = SW01AConst.NEW_TYPE == cbWOType.SelectedIndex;
            dgvMaterialList.Columns[CONG_LENH_SX_CT.N_SO_LO].Visible = SW01AConst.MODIFICATION_TYPE == cbWOType.SelectedIndex;
            btAddBTP.Enabled = SW01AConst.MODIFICATION_TYPE == cbWOType.SelectedIndex;
        }


        private bool IsNewWO()
        {
            return cbWOType.SelectedIndex == 0; // Index 0 : type of wo is new and 1 : modifying wo
        }

        // Create Work Order DTO
        public WorkOrderDTO CreateWODTO(int funcCd)
        {
            WorkOrderDTO woDTO = new WorkOrderDTO();
            if (funcCd == SW01AConst.F_ADD_CD)
            {
                // WO type
                woDTO.WOType = cbWOType.Text.Equals(SW01AConst.CB_NEW_TYPE) ? SW01AConst.NEW_TYPE : SW01AConst.MODIFICATION_TYPE;
                if (woDTO.WOType == SW01AConst.NEW_TYPE)
                {
                    woDTO.SoLanDieuChinh = 0;
                }
                woDTO.Status = checkBox_Pass.Checked;
                // WO info
                woDTO.DoMauN = Util.parseDouble(tbDoMauN.Text);
                woDTO.DoMauS = Util.parseDouble(tbDoMauS.Text);
                woDTO.DoSangN = Util.parseDouble(tbMauS.Text);
                woDTO.DoSangS = Util.parseDouble(tbDoSangS.Text);

                woDTO.HieuSuat = Util.parseDouble(tbHieuSuat.Text);
                woDTO.MauN = Util.parseDouble(tbMauN.Text);
                woDTO.MauS = Util.parseDouble(tbMauS.Text);
                woDTO.LotNo = tbLotNo.Text;

                woDTO.OrigianlLotNo = cbParentLotNo.Text;
                woDTO.ProductionDate = picProductionDate.Value.Date;
                woDTO.ProductNo = tbProductNo.Text;
                woDTO.SoE = tbSoE.Text;

                
                woDTO.SLTonAnToan = Util.parseDouble(tbSLTonAT.Text);
                woDTO.TongTien = Util.parseDouble(tbGiaCL.Text);

                // Material Info
                woDTO.MaterialList = (DataTable)dgvMaterialList.DataSource;
            }

            return woDTO;
        }

        private bool validate(int funcCd)
        {
            WOValidator validator = new WOValidator();
            string lotNo = tbLotNo.Text;
            if (WOValidator.IsEmpty(lotNo) || WOValidator.IsEmpty(tbProductNo.Text))
            {
                InforDialog.showMessageBox(trans.getMessageCaption(CommonConstantIF.ErrorBoxCap), trans.getMessageCaption(CommonConstantIF.REQUIRED_FIELD));
                return false;
            }

            // Original lot no must be defined if wo type is modification
            if (SW01AConst.MODIFICATION_TYPE == cbWOType.SelectedIndex)
            {
                if (cbParentLotNo.SelectedIndex < 0)
                {
                    InforDialog.showMessageBox(trans.getMessageCaption(CommonConstantIF.ErrorBoxCap), trans.getMessageCaption(CommonConstantIF.REQUIRED_FIELD));
                    return false;
                }
            }

            // Check material list
            if (dgvMaterialList.Rows.Count < 1)
            {
                InforDialog.showMessageBox(trans.getMessageCaption(CommonConstantIF.ErrorBoxCap), trans.getMessageCaption(CommonConstantIF.REQUIRED_FIELD));
                return false;
            }

            // Check lot no exist or not
            if (this.isNew && validator.ExistsLotNo(lotNo))
            {
                InforDialog.showMessageBox(trans.getMessageCaption(CommonConstantIF.ErrorBoxCap), trans.getMessageCaption(CommonConstantIF.SW01A_SO_LO_EXISTS));
                return false;
            }
            return true;
        }

        private void ResetFields()
        {
            tbLotNo.Text = CommonConstantIF.BLANK;
            tbProductNo.Text = CommonConstantIF.BLANK;
            picProductionDate.Value = DateTime.Today;
            this.matList.Rows.Clear();
            this.dgvMaterialList.DataSource = this.matList;
        }

        private void dgvMaterialList_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //string colName = dgvMaterialList.Columns[e.ColumnIndex].Name;
                //if (colName == CONG_LENH_SX_CT.N_TY_LE ||
                //    colName == CONG_LENH_SX_CT.N_TRONG_LUONG ||
                //    colName == CONG_LENH_SX_CT.N_SO_LAN)
                Type colType=dgvMaterialList.Columns[e.ColumnIndex].ValueType;
                if (colType == typeof(double) || colType == typeof(decimal))
                {
                    UserValidator.validateNumberOfCell(this, this.trans, e);
                    TotalOfWeight();
                }
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            List<DataRow> rows = Util.GetSelectedRows(this.matList);
            // Remove those selected rows in matList
            //foreach (DataGridViewRow dgvRow in dgvMaterialList.Rows)
            //{
            //    object chkVal = dgvRow.Cells[NGUYEN_VLIEU_VTU_DTO.N_CHON].Value;
            //    if (chkVal != null && chkVal.Equals(true))
            //    {
            //        string matNo = dgvRow.Cells[NGUYEN_VLIEU_VTU_DTO.N_MA_NVL_VTU].Value.ToString();
                    
            //        DataRow row = matList.Rows.Find(matNo);
            //        if (row != null)
            //        {
            //            rows.Add(row);
            //        }
            //    }
            //}

            //foreach (DataRow r in rows)
            //{
            //    matList.Rows.Remove(r);
            //}

            if (modelSW01.DeleteCLCT(tbLotNo.Text, matList, rows))
            {
                InforDialog.showInforBox(Owner, trans.getMessageCaption(CommonConstantIF.RemoveComplete), trans.getMessageCaption(CommonConstantIF.InforBoxCap));
            }
            else
                InforDialog.showErrorBox(Owner, trans.getMessageCaption(CommonConstantIF.RemoveError), trans.getMessageCaption(CommonConstantIF.ErrorBoxCap));
        }

        private void TotalOfWeight()
        {
            double sum = 0.0, num = 0.0;
            bool isModType = cbWOType.Text.Equals(SW01AConst.CB_MODIFICATION_TYPE);
            foreach (DataGridViewRow dgvRow in dgvMaterialList.Rows)
            {
                if (isModType && double.TryParse(dgvRow.Cells[CONG_LENH_SX_CT.N_TRONG_LUONG].Value.ToString(), out num))
                {
                    sum += num;
                }
                else if (!isModType && double.TryParse(dgvRow.Cells[CONG_LENH_SX_CT.N_TONG_LUONG_SX].Value.ToString(), out num))
                {
                    sum += num;
                }
            }
            this.tbTotal.Text = Util.parseString(sum);
        }

        private void dgvMaterialList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 &&
                (e.ColumnIndex == dgvMaterialList.Columns[CONG_LENH_SX_CT.N_TRONG_LUONG].Index ||
                 e.ColumnIndex == dgvMaterialList.Columns[CONG_LENH_SX_CT.N_TONG_LUONG_SX].Index ||
                 e.ColumnIndex == dgvMaterialList.Columns[CONG_LENH_SX_CT.N_SO_LAN].Index))
            {
                TotalOfWeight();
            }
        }

        private void dgvMaterialList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
    }
}
